<template>
  <div>
    <!-- 筛选框 -->
    <div style="margin-bottom: 10px;">
      <el-input v-model="StuClazzIvwVo.name" style="width: 120px;margin-right: 10px;" placeholder="请输入查询名称" clearable />
      <el-input v-model="StuClazzIvwVo.clazzId" placeholder="班级编号" clearable style="width: 100px; margin-right: 10px;" />
      <el-select filterable v-model="StuClazzIvwVo.stuStatus" placeholder="就业状态" clearable
        style="width: 140px; margin-right: 10px;" @change="list()">
        <el-option v-for="option in employmentStatusOptions" :key="option.value" :label="option.label"
          :value="option.value" />
      </el-select>
      <el-select filterable v-model="StuClazzIvwVo.isRes" placeholder="是否有简历" clearable
        style="width: 160px; margin-right: 10px;" @change="list()">
        <el-option label="有简历" value="有简历" />
        <el-option label="无简历" value="无简历" />
      </el-select>
      <el-button type="primary" @click="list()">筛选</el-button>
      <el-button @click="removeList()">重置</el-button>

      <!-- 批量导入 -->
      <el-upload :action="uploadUrl" :on-success="handleUploadSuccess" :on-error="handleUploadError"
        style="display: inline-block; margin-left: 10px;" :before-upload="beforeUpload" :show-file-list="false"
        accept=".xlsx, .xls">
        <el-button type="success">批量导入</el-button>
      </el-upload>

    </div>

    <div>
      <!-- 数据表格 - 简化显示 -->
      <el-table :row-class-name="tableRowClassName" :data="tableData" border style="width: 100%">
        <el-table-column prop="stuId" label="学生ID" width="100" />
        <el-table-column prop="stuName" label="姓名" width="100" />
        <el-table-column prop="stuGender" label="性别" />
        <el-table-column prop="stuAge" label="年龄" />
        <el-table-column prop="clazzName" label="班级" />
        <!-- 在表格中的就业状态列 -->
        <el-table-column prop="stuStatus" label="就业状态" width="120">
          <template #default="{ row }">
            {{ row.stuStatus || '未设置' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="450">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="showDetail(row)">详情</el-button>
            <el-button type="danger" size="small" @click="openPauseDialog(row.stuId)"
              v-if="row.stuStatus !== '推迟' && row.stuStatus !== '就业' && row.stuStatus !== '放弃'">暂停就业</el-button>
            <el-button type="success" size="small" @click="openRestoreDialog(row.stuId, row.clazzId)"
              v-if="row.stuStatus !== '就业中' && row.stuStatus !== '就业' && row.stuStatus !== '放弃'">恢复就业</el-button>
            <el-button type="warning" size="small" @click="openGiveUpDialog(row.stuId)"
              v-if="row.stuStatus !== '就业' && row.stuStatus !== '放弃'">放弃就业</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row.stuId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 学生详情对话框 -->
      <el-dialog v-model="detailDialogVisible" title="学生详细信息" width="700px">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="学生ID">{{ currentDetail.stuId }}</el-descriptions-item>
          <el-descriptions-item label="姓名">{{ currentDetail.stuName }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ currentDetail.stuGender }}</el-descriptions-item>
          <el-descriptions-item label="年龄">{{ currentDetail.stuAge }}</el-descriptions-item>
          <el-descriptions-item label="学历">{{ currentDetail.stuEdu }}</el-descriptions-item>
          <el-descriptions-item label="专业">{{ currentDetail.stuMajor }}</el-descriptions-item>
          <el-descriptions-item label="毕业时间">{{ formatTime(currentDetail.stuGrad) }}</el-descriptions-item>
          <el-descriptions-item label="班级名称">{{ currentDetail.clazzName }}</el-descriptions-item>
          <el-descriptions-item label="班主任">{{ currentDetail.clazzTeacher }}</el-descriptions-item>
          <el-descriptions-item label="项目经理">{{ currentDetail.clazzManager }}</el-descriptions-item>
          <el-descriptions-item label="计算结束时间">{{ formatTime(currentDetail.clazzEnd) }}</el-descriptions-item>
          <el-descriptions-item label="就业状态">
            {{ currentDetail.stuStatus || '未设置' }}
          </el-descriptions-item>
          <el-descriptions-item label="简历ID">{{ currentDetail.resId }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatTime(currentDetail.created) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatTime(currentDetail.updated) }}</el-descriptions-item>
        </el-descriptions>
        <!-- 添加底部退出按钮 -->
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="detailDialogVisible = false">退出</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 暂停就业对话框 -->
      <el-dialog v-model="pauseDialogVisible" title="申请暂停就业" width="400px">
        <el-form :model="pauseForm" label-width="120px">
          <el-form-item label="暂停原因">
            <el-input v-model="pauseForm.delayReason" placeholder="请输入暂停就业原因" clearable />
          </el-form-item>
          <el-form-item label="暂停时间">
            <el-date-picker v-model="pauseForm.delayDate" type="date" placeholder="请选择暂停时间" value-format="YYYY-MM-DD"
              style="width: 100%;" />
          </el-form-item>
          <el-form-item label="预计开始就业时间">
            <el-date-picker v-model="pauseForm.delayStart" type="date" placeholder="请选择预计开始就业时间" value-format="YYYY-MM-DD"
              style="width: 100%;" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="pauseDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitPause()">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 恢复就业对话框 -->
      <el-dialog v-model="restoreDialogVisible" title="申请恢复就业" width="400px">
        <el-form :model="restoreForm" label-width="120px">
          <el-form-item label="实际开始就业时间">
            <el-date-picker v-model="restoreForm.newStartDate" type="date" placeholder="请选择开始就业时间"
              value-format="YYYY-MM-DD" style="width: 100%;" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="restoreDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitRestore()">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>

    <!-- 分页 -->
    <div class="demo-pagination-block">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElButton, ElTable, ElTableColumn, ElMessage, ElMessageBox, ElUpload, ElDescriptions, ElDescriptionsItem } from 'element-plus';
import {  filterStudentApi, deleteStudentApi, pauseEmploymentApi, restoreEmploymentApi, uploadApi, abandonEmploymentApi } from '@/api/stu-api';

//分页参数
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(10);

// 表格数据
const tableData = ref([]);

// 就业状态选项
const employmentStatusOptions = [
  { value: '就业', label: '就业' },
  { value: '就业中', label: '就业中' },
  { value: '推迟', label: '推迟' },
  { value: '放弃', label: '放弃' },
  { value: '推就业中', label: '推就业中' },
];

// 详情对话框控制变量
const detailDialogVisible = ref(false);
const currentDetail = ref<any>({
});

// 格式化时间的方法  去掉T
const formatTime = (time: string) => {
  if (!time) return '';
  return time.replace('T', ' ');
}


//对象
const StuClazzIvwVo = ref({
  clazzId: '',
  stuStatus: '推迟',
  isRes: '无简历',
  name: '',
  page: 1,
  size: 10,
});



// 显示学生详情
const showDetail = (row: any) => {
  currentDetail.value = { ...row };
  detailDialogVisible.value = true;
};

// 查询列表
const list = async () => {
  StuClazzIvwVo.value.page = currentPage.value;
  StuClazzIvwVo.value.size = pageSize.value;
  // 分页模糊查询参数
  const response = await filterStudentApi(StuClazzIvwVo.value);
  console.log('查询列表', response);
  if (response.code === 200) {
    tableData.value = response.data.list;
    total.value = response.data.total;
  } else {
    ElMessage.error('查询失败');
  }
};


//返回列表
const removeList = async () => {
  StuClazzIvwVo.value.clazzId = '';
  StuClazzIvwVo.value.stuStatus = '推迟';
  StuClazzIvwVo.value.isRes = '无简历';
  StuClazzIvwVo.value.name = '';
  StuClazzIvwVo.value.page = 1;
  StuClazzIvwVo.value.size = 10;
  list();
};


// 处理每页显示条数变化的事件
const handleSizeChange = (newPageSize: number) => {
  pageSize.value = newPageSize;
  list();
};

// 处理当前页码变化的事件
const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage;
  list();
};

// 上传 URL
const uploadUrl = ref('/student/upload');

// 文件上传成功回调
const handleUploadSuccess = (response: any, file: File, fileList: File[]) => {

  if (response.code === 200) {
    ElMessage.success('导入成功');
    list(); // 刷新表格数据
  } else {
    ElMessage.error(response.message || '导入失败');
  }
  return undefined;
};

// 文件上传失败回调
const handleUploadError = (err: Error, file: File, fileList: File[]) => {
  err
  file
  fileList
  ElMessage.error('文件上传失败，请稍后再试');
  return undefined;
};

// 上传前校验文件格式
const beforeUpload = async (file: File) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
    file.type === 'application/vnd.ms-excel';
  if (!isExcel) {
    ElMessage.error('只能上传 Excel 文件');
    return false;
  }

  const formData = new FormData();
  formData.append('file', file);

  try {
    const response = await uploadApi(formData);
    console.log('上传前校验文件格式', response);
    if (response.code === 200) {
      ElMessage.success('导入成功');
      await list(); // 刷新表格数据
    } else {
      ElMessage.error(response.msg || '导入失败');
    }
  } catch (error) {
    ElMessage.error('文件上传失败，请稍后再试');
  }

  return false; // 阻止默认上传行为
};

// 删除学生信息
const handleDelete = async (id: number) => {
  try {
    // 弹出确认对话框
    await ElMessageBox.confirm(
      '确认删除该学生信息吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    // 调用删除接口
    const response = await deleteStudentApi(id);
    if (response.code === 200) {
      ElMessage.success('删除成功');
      list(); // 刷新表格数据
    } else {
      ElMessage.error(response.data?.message || '删除失败');
    }
  } catch (error) {
    if (error === 'cancel') {
      // 用户点击了取消按钮
      ElMessage.info('已取消删除');
    } else {
      // 其他错误（如网络错误或后端异常）
      console.error('删除失败:', error);
      ElMessage.error('删除失败，请稍后再试');
    }
  }
};

// 暂停就业对话框控制变量
const pauseDialogVisible = ref(false);
const pauseSelectedStuId = ref<number | null>(null);

// 暂停就业表单数据
const pauseForm = ref({
  delayReason: '', // 暂停原因
  delayDate: '', // 暂停时间
  delayStart: '', // 预计开始就业时间
});

// 打开暂停就业对话框
const openPauseDialog = (stuId: number) => {
  pauseSelectedStuId.value = stuId;
  pauseForm.value = { delayReason: '', delayDate: '', delayStart: '' }; // 清空表单
  pauseDialogVisible.value = true;
};

// 提交暂停就业信息
const submitPause = async () => {
  try {
    // 校验表单是否填写完整
    if (!pauseForm.value.delayReason.trim()) {
      ElMessage.error('请填写暂停就业原因');
      return;
    }
    if (!pauseForm.value.delayDate) {
      ElMessage.error('请选择暂停时间');
      return;
    }
    if (!pauseForm.value.delayStart) {
      ElMessage.error('请选择预计开始就业时间');
      return;
    }

    // 验证预计开始时间是否晚于暂停时间
    const delayDate = new Date(pauseForm.value.delayDate);
    const delayStart = new Date(pauseForm.value.delayStart);
    if (delayStart <= delayDate) {
      ElMessage.error('预计开始就业时间必须晚于暂停时间');
      return;
    }

    // 构造 Delay 对象
    const delay = {
      stuId: pauseSelectedStuId.value,
      delayReason: pauseForm.value.delayReason,
      delayDate: pauseForm.value.delayDate,
      delayStart: pauseForm.value.delayStart,
    };

    console.log('提交暂停就业信息:', delay);
    // 调用 API 方法
    const response = await pauseEmploymentApi(delay);
    console.log('提交暂停就业信息:', response);
    // 处理响应
    if (response.code === 200) {
      ElMessage.success('暂停就业成功');
      list(); // 刷新表格数据
      pauseDialogVisible.value = false; // 关闭对话框
    } else {
      ElMessage.error(response.data.message || '暂停就业失败');
    }
  } catch (error) {
    console.error('暂停就业失败:', error);
    ElMessage.error('暂停就业失败，请稍后再试');
  }
};

// 定义恢复就业信息的请求参数类型
export interface RestoreEmploymentVo {
  stuId: number; // 学生ID
  clazzId: number; // 班级ID
  newStartDate: string; // 新的就业时间（ISO 格式）
}

// 恢复就业对话框控制变量
const restoreDialogVisible = ref(false);
const restoreSelectedStuId = ref<number | null>(null);
const restoreSelectedClazzId = ref<number | null>(null);

// 恢复就业表单数据
const restoreForm = ref({
  newStartDate: '', // 新的就业时间
});

// 打开恢复就业对话框
const openRestoreDialog = (stuId: number, clazzId: number) => {
  restoreForm.value.newStartDate = ''; // 清空表单
  restoreSelectedStuId.value = stuId;
  restoreSelectedClazzId.value = clazzId;
  restoreDialogVisible.value = true;
};

// 提交恢复就业信息
const submitRestore = async () => {
  try {
    // 校验表单是否填写完整
    if (!restoreForm.value.newStartDate) {
      ElMessage.error('请选择新的就业时间');
      return;
    }

    // 构造 Restore 对象
    const restoreData: RestoreEmploymentVo = {
      stuId: restoreSelectedStuId.value!,
      clazzId: restoreSelectedClazzId.value!,
      newStartDate: restoreForm.value.newStartDate,
    };
    console.log('提交恢复就业信息:', restoreData);

    // 调用 API 方法
    const response = await restoreEmploymentApi(restoreData);

    // 处理响应
    if (response.code === 200) {
      ElMessage.success('恢复就业成功');
      list(); // 刷新表格数据
      restoreDialogVisible.value = false; // 关闭对话框
      restoreForm.value.newStartDate = ''; // 清空表单
    } else {
      ElMessage.error(response.data?.message || '恢复就业失败');
    }
  } catch (error) {
    console.error('恢复就业失败:', error);
    ElMessage.error('恢复就业失败，请稍后再试');
  }
};

// 放弃就业
const openGiveUpDialog = async (stuId: any) => {
  try {
    // 弹出确认对话框
    await ElMessageBox.confirm(
      '确认放弃就业吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    // 调用删除接口
    const response = await abandonEmploymentApi({ stuId: stuId });
    console.log('放弃就业', response);
    if (response.code === 200) {
      ElMessage.success('放弃成功');
      list(); // 刷新表格数据
    } else {
      ElMessage.error(response.data?.message || '放弃失败');
    }
  } catch (error) {
    if (error === 'cancel') {
      // 用户点击了取消按钮
      ElMessage.info('已取消删除');
    } else {
      // 其他错误（如网络错误或后端异常）
      console.error('放弃失败:', error);
      ElMessage.error('放弃失败，请稍后再试');
    }
  }
}


// 页面加载完后，加载默认数据
onMounted(() => {
  list();
});

// 表格行样式
const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: any
  rowIndex: number
}) => {
  row
  if (rowIndex % 2 === 0) {
    return 'success-row'
  }
  return ''
}

</script>

<style>
.demo-pagination-block {
  margin-top: 10px;
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>